package dbexp.connection;

import static dbexp.utils.Error.access_property;
import static dbexp.utils.Error.sql;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import dbexp.connection.model.ConnectionInfo;
import dbexp.utils.DbProperties;

public class ConnectionPool {
	private static Map<ConnectionInfo, PoolManager<DbConnection>> pools = new HashMap<ConnectionInfo, PoolManager<DbConnection>>();
	private static Map<String, Driver> drivers = new HashMap<String, Driver>();
	private static List<DbConnection> connections = new ArrayList<DbConnection>();
	
	public static DbConnection getConnection(ConnectionInfo info) throws PoolManagerException, DbStateException, DbAccessException{
		PoolManager<DbConnection> userPool = pools.get(info);
		if(userPool == null){
			userPool = new PoolManager<DbConnection>();
			pools.put(info, userPool);
		}
		if(userPool.isEmpty()){
			userPool.add(createConnection(info));
		}
		DbConnection userCon = userPool.get();
		if(userCon == null){
			userCon = createConnection(info);
			userPool.add(userCon);
			userCon = userPool.get();
		}
		return userCon;
	}
	public static void releaseConnection(ConnectionInfo info, DbConnection con){
		PoolManager<DbConnection> userPool = pools.get(info);
		if(userPool != null){
			userPool.release(con);
		}
	}
	public static void closeAllConnections(){
		for(PoolManager<DbConnection> pool : pools.values()){
			for(DbConnection con : connections){
				pool.release(con);
			}
			for(int closed = 0; pool.getSize()!=closed;){
				try {
					DbConnection con = pool.get();
					if (con != null && !con.isClosed()) {
						con.close();closed++;
					}
				}
				catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	private static Driver getDriver(ConnectionInfo info) throws PoolManagerException, DbStateException{
		final String driverName = info.getDriverName();
		Driver out = drivers.get(driverName);
		if(out == null){
			try{
				final Class<?> driverClass = Class.forName(driverName);
				out = (Driver) driverClass.newInstance();
			} catch (final ClassNotFoundException exc) {
				throw new PoolManagerException(
						"Nie można załadować sterownika bazy danych.("
								+ exc.getMessage() + ")");
			} catch (final InstantiationException exc) {
				throw new PoolManagerException(
						"Nie można utworzyć instancji sterownika bazy danych.("
								+ exc.getMessage() + ")");
			} catch (final IllegalAccessException exc) {
				throw new PoolManagerException(
						"Brak dostępu do instancji sterownika bazy danych.("
								+ exc.getMessage() + ")");
			}
			drivers.put(driverName, out);
		}
		return out;
	}
	
	private static DbConnection createConnection(ConnectionInfo info) throws PoolManagerException, DbStateException, DbAccessException{
		DbConnection out = null;
		Connection con = null;
		try {
			final Driver driver = getDriver(info);
			final String passwordInClearText = info.getPassword();
			final Properties props = new Properties();
			props.put("user", info.getUsername());
			props.put("password", passwordInClearText);
	
			con = driver.connect(info.getDatabaseURL(),	props);
			if (con == null) {
				throw new DbBadPropertiesAccessException(
						access_property.format(DbProperties.getInstance()
								.getDrivertName(), info
								.getDatabaseURL()));
			}
			if(DatabaseType.ORACLE.is(con.getMetaData().getDatabaseProductName())){
				out = new OracleConnection(info, con);
			}else{
				out = new DbConnection(info, con);
			}
			connections.add(out);
		} catch (final SQLException exc) {
			System.out.println(sql.state(exc));
			sql.throwDbStateException(exc);
		} catch (final DbBadPropertiesAccessException e) {
			throw new PoolManagerException(
					"Błędny sposób połaczenia ze sterownikiem:"
							+ DbProperties.getInstance().getDrivertName()
							+ " z użyciem adresu:"
							+ info.getDatabaseURL());
		}
		return out;
	}
	private enum DatabaseType{
		ORACLE("Oracle");
		private String toString = "";
		private DatabaseType(){
			toString = name();
		}
		private DatabaseType(String toString){
			this.toString = toString;
		}
		public boolean is(String databaseName){
			return toString.equals(databaseName);
		}
	}
}
